// 获取DOM元素
const uploadSection = document.getElementById('uploadSection');
const fileInput = document.getElementById('fileInput');
const status = document.getElementById('status');
const progress = document.getElementById('progress');
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');
const filesContainer = document.getElementById('files');

// 拖拽上传事件监听
uploadSection.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadSection.classList.add('dragover');
});

uploadSection.addEventListener('dragleave', () => {
    uploadSection.classList.remove('dragover');
});

uploadSection.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadSection.classList.remove('dragover');
    const files = e.dataTransfer.files;
    uploadFiles(files);
});

// 文件选择事件监听
fileInput.addEventListener('change', (e) => {
    uploadFiles(e.target.files);
});

/**
 * 上传文件函数
 * @param {FileList} files - 要上传的文件列表
 */
function uploadFiles(files) {
    if (files.length === 0) return;

    const formData = new FormData();
    for (let file of files) {
        formData.append('file', file);
    }

    // 显示进度条
    progress.style.display = 'block';
    progressBar.style.width = '0%';
    progressText.textContent = '准备上传...';

    // 使用 XMLHttpRequest 来支持进度监控
    const xhr = new XMLHttpRequest();

    // 监听上传进度
    xhr.upload.addEventListener('progress', function (e) {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            progressBar.style.width = percentComplete + '%';
            progressText.textContent = `上传中... ${percentComplete.toFixed(1)}% (${formatFileSize(e.loaded)} / ${formatFileSize(e.total)})`;
        }
    });

    // 监听上传完成
    xhr.addEventListener('load', function () {
        if (xhr.status === 200) {
            try {
                const data = JSON.parse(xhr.responseText);
                showStatus('文件上传成功！', 'success');
                progress.style.display = 'none';
                loadFileList();
            } catch (error) {
                showStatus('文件上传成功，但解析响应失败', 'success');
                progress.style.display = 'none';
                loadFileList();
            }
        } else if (xhr.status === 413) {
            showStatus('文件太大，超过服务器限制', 'error');
            progress.style.display = 'none';
        } else if (xhr.status === 507) {
            showStatus('服务器磁盘空间不足', 'error');
            progress.style.display = 'none';
        } else {
            let errorMessage = '文件上传失败: HTTP ' + xhr.status;
            try {
                const errorData = JSON.parse(xhr.responseText);
                if (errorData && errorData.message) {
                    errorMessage = errorData.message;
                }
            } catch (e) {
                // 如果无法解析错误响应，使用默认消息
            }
            showStatus(errorMessage, 'error');
            progress.style.display = 'none';
        }
    });

    // 监听上传错误
    xhr.addEventListener('error', function () {
        showStatus('文件上传失败: 网络错误', 'error');
        progress.style.display = 'none';
    });

    // 监听上传中止
    xhr.addEventListener('abort', function () {
        showStatus('文件上传已取消', 'error');
        progress.style.display = 'none';
    });

    // 设置超时时间 (30分钟)
    xhr.timeout = 30 * 60 * 1000;

    // 监听超时
    xhr.addEventListener('timeout', function () {
        showStatus('文件上传超时，请检查网络连接', 'error');
        progress.style.display = 'none';
    });

    // 开始上传
    xhr.open('POST', '/api/file/upload');
    xhr.send(formData);
}

/**
 * 显示状态消息
 * @param {string} message - 消息内容
 * @param {string} type - 消息类型 ('success' 或 'error')
 */
function showStatus(message, type) {
    status.innerHTML = `<div class="status ${type}">${message}</div>`;
    setTimeout(() => {
        status.innerHTML = '';
    }, 5000);
}

/**
 * 加载文件列表
 */
function loadFileList() {
    fetch('/api/file/list')
        .then(response => response.json())
        .then(files => {
            filesContainer.innerHTML = '';
            files.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <div class="file-info">
                        <div class="file-name">${file.name}</div>
                        <div class="file-size">${formatFileSize(file.size)} - ${new Date(file.lastModified).toLocaleString()}</div>
                    </div>
                    <div class="file-actions">
                        <a href="/api/file/download/${encodeURIComponent(file.name)}" class="download-btn" download>下载</a>
                        <button class="delete-btn" onclick="deleteFile('${file.name}')">删除</button>
                    </div>
                `;
                filesContainer.appendChild(fileItem);
            });
        })
        .catch(error => {
            console.error('加载文件列表失败:', error);
        });
}

/**
 * 删除文件
 * @param {string} fileName - 要删除的文件名
 */
function deleteFile(fileName) {
    if (!confirm(`确定要删除文件 "${fileName}" 吗？此操作不可撤销。`)) {
        return;
    }

    fetch(`/api/file/delete/${encodeURIComponent(fileName)}`, {
        method: 'DELETE'
    })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
        })
        .then(data => {
            showStatus(`文件 "${fileName}" 删除成功！`, 'success');
            loadFileList(); // 重新加载文件列表
        })
        .catch(error => {
            console.error('删除文件失败:', error);
            showStatus(`删除文件失败: ${error.message}`, 'error');
        });
}

/**
 * 格式化文件大小
 * @param {number} bytes - 字节数
 * @returns {string} 格式化后的文件大小
 */
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 页面加载时获取文件列表
document.addEventListener('DOMContentLoaded', function () {
    loadFileList();
}); 